package com.aos.util;


import org.apache.commons.codec.digest.DigestUtils;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

public abstract class SystemUtils {

    /** 1.有效状态 */
    public static final String VALID = "1";
    /** 0.无效状态 */
    public static final String INVALID = "0";

    /** 1.是/yes */
    public static final String YES = "1";
    /** 0.是/no */
    public static final String NO = "0";

    /**
     * 转换obj为字符串,除去了前后的空格,为空则使用defaultValue
     *
     * @param obj
     * @param defaultValue
     * @return
     */
    public static String trim(Object obj, String defaultValue) {
        return isEmpty(obj) ? defaultValue.trim() : obj.toString().trim();
    }

    /**
     * 判断对象是否为空.
     *
     * <pre>
     * 如果obj为字符串,且全部为空白字符,则返回true.
     * 如果是数组,则0长度的数组也视为空.
     * Collection/Map则直接返回isEmpty()
     * </pre>
     *
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            // 字符串判断是否为0字节或全空白
            return ((String) obj).trim().length() == 0;
        }
        if (obj instanceof StringBuilder || obj instanceof StringBuffer) {
            // 同字符串
            return obj.toString().trim().length() == 0;
        }
        if (obj instanceof CharSequence) {
            // CharSequence
            return ((CharSequence) obj).length() == 0;
        }

        if (obj.getClass().isArray()) {
            // 数组
            return Array.getLength(obj) == 0;
        }
        if (obj instanceof Collection) {
            // 集合
            return ((Collection<?>) obj).isEmpty();
        }
        if (obj instanceof Map) {
            // Map
            return ((Map<?, ?>) obj).isEmpty();
        }
        if(obj instanceof Set) {
            //set
            return ((Set<?>) obj).isEmpty();
        }
        return false;
    }

    /**
     * 数组转换为逗号分隔的字符串,可用于cache的key.
     *
     * @param args 数组
     * @param startIndex 起始位置
     * @param prefix 需要添加的前缀
     * @return
     */
    public static String toString(Object[] args, final int startIndex, final String prefix) {
        if (args == null) {
            // 数组为null或者最大下标小于startIndex
            return "";
        }
        int iMax = args.length - 1;
        if(iMax < startIndex) {
            return "";
        }
        if (iMax == startIndex) {
            return (prefix == null ? "" : prefix) + args[startIndex];
        }

        iMax = iMax - startIndex + 1;
        Object[] a = new Object[iMax];
        System.arraycopy(args, startIndex, a, 0, iMax);
        try {
            Arrays.sort(a); // 为数组排序
        } catch (Exception e) {
            // TODO 可能a无法排序,不处理
        }
        StringBuilder b = new StringBuilder(prefix == null ? "" : prefix);

        iMax = iMax - 1;
        for (int i = 0;; i++) {
            b.append(args[i]);
            if (i == iMax) {
                return b.toString();
            }
            b.append(",");
        }
    }



    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     * @date 2017-3-7
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }


    /**
     * 字符串空处理包括"null"字符串
     * @param obj
     * @return obj字符串对象
     * @author LiXiaobo
     * @date 2017-3-10
     */
    public static Object objectTtoString(Object obj){
        if(obj == null || "".equals(obj.toString())
                || "null".equals(obj.toString()) || "NULL".equals(obj.toString())){
            return "";
        }
        return obj;
    }

    /**
     * @Title: replaceStr
     * @Description:mysql t特殊字符替换 MYSQL数据库匹配不需要再加百分号
     * @param: @return
     * @return: String
     * @throws
     */
    public static String replaceStr(String str) {
        if (isEmpty(str)) {
            return "";
        }
        return str.replaceAll("\\[", "\\[\\[\\]").replaceAll("_", "\\[_\\]").replaceAll("%", "\\[%\\]");
    }

    /**
     * 加密密码字符串
     *
     * @return: String
     * @throws
     */
    public static String getPasswordEncoder(String password, String salt) {
        String newpassword = password + "{" + salt + "}";
        return DigestUtils.md5Hex(newpassword);
    }

    /**
     * 明文密码加密密码字符串
     * @param clearPwd:明文密码
     * @param salt
     * @return
     */
    public static String getClearPasswordEncoder(String clearPwd, String salt){
        return getPasswordEncoder(DigestUtils.md5Hex(clearPwd), salt);
    }

    public static String getMD5(String sMessage) {
        byte[] defaultBytes = sMessage.getBytes();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte[] messageDigest = algorithm.digest();
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
    }

    /**
     * 生成uuid
     * @return
     */
    public static String UUID(){
        return UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
    }


    /**
     * 获取Integer默认值
     * @param obj
     * @param dafultValue
     * @return
     */
    public static Integer getIntIfEmpty(Object obj, int dafultValue) {
        if(isEmpty(obj)){
            return dafultValue;
        }else{
            if(obj instanceof String) {
                return Integer.parseInt((String)obj);
            }
            return (Integer) obj;
        }
    }

    /**
     * 获取String默认值
     * @param obj
     * @param dafultValue
     * @return
     */
    public static String getStringIfEmpty(Object obj, String dafultValue) {
        if(isEmpty(obj)){
            return dafultValue;
        }
        return (String) obj;
    }

    /**
     * 超过长度中间省略用星号代替
     * @param length 指定长度(至少大于10)
     * @return
     */
    public static String asteriskProcessing(String str,int length){
        if(str != null && str.length() > length && str.length() > 10){
            str = str.substring(0,3) + "***" + str.substring(str.length()-3,str.length());
        }
        return str;
    }

}
